#include "snowboy/snowboy-detect-c-wrapper.h"
#include <stdlib.h>
#include <stdio.h>
#include "record.h"
#include <time.h>

#define SILENCE_THRESHOLD 100 // 静音阈值
#define SILENCE_DURATION 5 // 静音持续时间（秒）

int main()
{
    // 创建唤醒词检测器
    SnowboyDetect* detector = SnowboyDetectConstructor("common.res","xiaojin.pmdl");
    if(!detector)
    {
        return EXIT_FAILURE;
    }

    SnowboyDetectSetSensitivity(detector,"0.6");

    // 获取检测器参数
    int bits = SnowboyDetectBitsPerSample(detector); // 采样深度
    int channels = SnowboyDetectNumChannels(detector); // 声道数量
    int rate = SnowboyDetectSampleRate(detector); // 采样频率

    printf("采样深度: %d\n",bits);
    printf("声道数量: %d\n",channels);
    printf("采样频率：%d\n",rate);

    // 打开音频采集设备
    snd_pcm_uframes_t period;
    snd_pcm_t* capture = record_open("hw:0,0",SND_PCM_FORMAT_S16_LE, channels, rate, &period);
    if(!capture)
    {
        return EXIT_FAILURE;
    }

    char* buffer = malloc(snd_pcm_frames_to_bytes(capture, period)); // 分配缓冲区
    if (!buffer) {
        perror("malloc");
        record_close(capture);
        return EXIT_FAILURE;
    }

    int recording = 0;
    FILE *fp = NULL; // 录音文件

    while(1)
    {
        snd_pcm_sframes_t frames = snd_pcm_readi(capture, buffer, period); // 从PCM设备读取数据
        if (frames < 0)
        {
            fprintf(stderr, "Error from read: %s\n", snd_strerror(frames));
            snd_pcm_recover(capture, frames, 0);
            continue;
        }

        int status = SnowboyDetectRunDetection(detector, (int16_t*)buffer, snd_pcm_frames_to_bytes(capture, frames), 0);
        if (status > 0 && !recording)
        {
            printf("检测到小靖小靖，开始录音...\n");
            fp = fopen("recorded_audio.wav", "wb");
            if (!fp)
            {
                perror("fopen");
                free(buffer);
                record_close(capture);
                SnowboyDetectDestructor(detector);
                return EXIT_FAILURE;
            }
            recording = 1;
        }

        if (recording)
        {
            fwrite(buffer, snd_pcm_frames_to_bytes(capture, frames), 1, fp); // 将读取的数据写入文件

            // 检查静音状态
            static int silence_frames = 0;
            int16_t* samples = (int16_t*)buffer;
            int silence = 1;

            for (int i = 0; i < snd_pcm_frames_to_bytes(capture, frames) / sizeof(int16_t); ++i)
            {
                if (abs(samples[i]) > SILENCE_THRESHOLD)
                {
                    silence = 0;
                    silence_frames = 0;
                    break;
                }
            }

            if (silence)
            {
                silence_frames += frames;
                if ((silence_frames / rate) >= SILENCE_DURATION)
                {
                    printf("静音持续时间达到 %d 秒，停止录音。\n", SILENCE_DURATION);
                    fclose(fp);
                    recording = 0;
                    silence_frames = 0;
                    break;
                }
            }
        }

        printf("检测状态: %d\n", status);
    }

    free(buffer);
    record_close(capture);
    SnowboyDetectDestructor(detector);
    return EXIT_SUCCESS;
}
